package team.seekers.oj.group.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import team.seekers.oj.common.annotation.UserSession;
import team.seekers.oj.common.entity.ApiResponseBody;
import team.seekers.oj.common.entity.PageResult;
import team.seekers.oj.common.entity.UserSessionDTO;
import team.seekers.oj.common.enums.ApiExceptionEnum;
import team.seekers.oj.common.util.AssertUtils;
import team.seekers.oj.group.dto.GroupCreateReqDTO;
import team.seekers.oj.group.dto.GroupListDTO;
import team.seekers.oj.group.dto.GroupListReqDTO;
import team.seekers.oj.group.dto.GroupManageDTO;
import team.seekers.oj.group.entity.pa.GroupQuery;
import team.seekers.oj.group.entity.vo.GroupInfoVO;
import team.seekers.oj.group.service.GroupExtensionService;
import team.seekers.oj.group.service.GroupService;
import team.seekers.oj.group.utils.DemoDataListener;
import team.seekers.oj.group.utils.StudentExcel;
import team.seekers.oj.user.service.UserService;

import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/group")
public class GroupController {

    @Autowired
    private GroupService groupService;

    @Autowired
    private UserService userService;

    @Autowired
    private GroupExtensionService groupExtensionService;


    @GetMapping("/info")
    @ApiResponseBody
    public GroupInfoVO query(@RequestParam("id") long id) {
        return groupService.getVO(id);
    }

    /**
     * 条件查询与自己相关的所有群组（学生加入的，教师创建的）
     */
    @PostMapping("/page/mine")
    @ApiResponseBody
    public PageResult<GroupListDTO> page(@RequestBody @Valid GroupQuery query,
                                         @UserSession UserSessionDTO userSessionDTO) {
        GroupListReqDTO groupListReqDTO = new GroupListReqDTO();
        BeanUtils.copyProperties(query,groupListReqDTO);
        if(userSessionDTO.isStudent()){
            groupListReqDTO.setStudentId(userSessionDTO.getUserId());
        }else{
            groupListReqDTO.setTeacherId(userSessionDTO.getUserId());
        }
        return groupService.page(groupListReqDTO);
    }


    /**
     * 学生主动加入某个群组（直接输入id加入）
     */
    @GetMapping("/in")
    @ApiResponseBody
    public Void join(@RequestParam("groupId") long groupId,
                     @UserSession UserSessionDTO userSessionDTO) {
        groupService.addUser(groupId,userSessionDTO.getUserId());
        return null;
    }

    /**
     * 学生主动退出某个群组
     */
    @GetMapping("/out")
    @ApiResponseBody
    public Void out(@RequestParam("groupId") long groupId,
                    @UserSession UserSessionDTO userSessionDTO) {
        groupService.removeUser(groupId,userSessionDTO.getUserId());
        return null;
    }


    /**
     * 教师添加某个群组成员
     */
    @GetMapping("/studentIn")
    @ApiResponseBody
    public Void studentIn(@RequestParam("groupId") long groupId,
                     @RequestParam("studentId") long studentId,
                     @UserSession UserSessionDTO userSessionDTO) {
        // 创建者才可修改群组
        AssertUtils.isTrue(groupService.isGroupManager(groupId, userSessionDTO),
                ApiExceptionEnum.USER_NOT_MATCHING, "没有权限");
        groupService.addUser(groupId,studentId);
        return null;
    }

    /**
     * 教师批量添加某个群组成员
     */

    @PostMapping("studentsIn")
    public Void plUpdate(@RequestParam("groupId") long groupId,
                         @RequestParam("students") MultipartFile file) throws IOException {
        //文件输入流
        InputStream in = file.getInputStream();
        //调用方法进行读取
        EasyExcel.read(in, StudentExcel.class,new DemoDataListener(groupId,groupService,userService)).sheet().doRead();
        return null;
    }


    /**
     * 教师删除某个群组成员
     */
    @GetMapping("/studentOut")
    @ApiResponseBody
    public Void studentOut(@RequestParam("groupId") long groupId,
                     @RequestParam("studentId") long studentId,
                     @UserSession UserSessionDTO userSessionDTO) {
        // 创建者才可修改群组
        AssertUtils.isTrue(groupService.isGroupManager(groupId, userSessionDTO),
                ApiExceptionEnum.USER_NOT_MATCHING, "没有权限");
        groupService.removeUser(groupId,studentId);
        return null;
    }


    /**
     * 教师创建群组
     */
    @PostMapping("/create")
    @ApiResponseBody
    public Long create(@RequestBody @Valid GroupCreateReqDTO reqDTO,
                       @UserSession UserSessionDTO userSessionDTO) {
        // 增补
        reqDTO.setUserId(userSessionDTO.getUserId());

        List<Long> userIds = Optional.ofNullable(reqDTO.getUsers()).orElse(Lists.newArrayList());
        reqDTO.setUsers(userIds.stream().distinct().collect(Collectors.toList()));

        return groupService.create(reqDTO);
    }

    /**
     * 教师修改群组
     */
    @PostMapping("/update")
    @ApiResponseBody
    public Void update(@RequestBody @Valid GroupManageDTO reqDTO,
                       @UserSession UserSessionDTO userSessionDTO) {
        // 创建者才可修改群组
        AssertUtils.isTrue(groupService.isGroupManager(reqDTO.getUserId(), userSessionDTO),
                ApiExceptionEnum.USER_NOT_MATCHING, "没有权限");

        List<Long> users = Optional.ofNullable(reqDTO.getUsers()).orElse(Lists.newArrayList());
        reqDTO.setUsers(users.stream().distinct().collect(Collectors.toList()));

        groupService.update(reqDTO);
        return null;
    }



}